<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use \think\helper\Str;
use think\Session;
// 应用公共文件
/**
 * 用户头像URL
 * @Author zhanghong
 * @Date   2017-01-16
 * @param  [type]     $user_avatar [description]
 * @return [type]           [description]
 */
function show_user_avatar_url($user_avatar){
  if(is_array($user_avatar) || is_object($user_avatar)){
    if(isset($user_avatar['avatar'])){
      $img_path = $user_avatar['avatar'];
    }else{
      $img_path = null;
    }
  }else{
    $img_path = $user_avatar;
  }

  if(empty($img_path)){
    $img_path = '/static/index/images/1.png';
  }

  return $img_path;
}


/**
 * 读取网站设置
 * @Author zhanghong
 * @Date   2017-01-03
 */
function settings(){
  $list = \think\Db::name('options')->select();
  foreach ($list as $key => $opt) {
    $val = json_decode($opt['value'], true);
    think\Config::set($opt['name'], $val);
  }
}

// 应用公共文件
function get_field_text($field_name, $val){
  switch ($field_name) {
  case 'status':
    $list = list_field_status();
    break;
  case 'menu_status':
    $list = list_field_menu_status();
    break;
  case 'article_type':
    $list = list_field_article_type();
    break;
  default:
    $list = [];
    break;
  }

  if($list[$val]){
    return $list[$val];
  }else{
    return $val;
  }
}

/**
* 格式化显示时间
* @param int_time string 时间值
* @param type string 输入格式
* @return string
*/
function format_show_time($int_time, $type = ''){
  if(empty($int_time)){
    return '';
  }else if(is_numeric($int_time)){
    switch ($type) {
    case 'zh_time':
      $format_str = 'm月d日 H:i:s';
      break;
    case 'no_second':
      $format_str = 'Y-m-d H:i';
      break;
    case 'date_node':
      $format_str = 'Y.m.d';
      break;
    case 'small_date_node':
      $format_str = 'y.m.d';
      break;
    case 'no_year_node':
      $format_str = 'm.d H:i:s';
      break;
    case 'short_node':
      $format_str = 'm.d';
      break;
    case 'only_date':
      $format_str = 'Y-m-d';
      break;
    case 'month_day':
      $format_str = 'm-d';
      break;
    case 'date_dir':
      $format_str = 'Y/m/d';
      break;
    case 'ymd_dir':
      $format_str = 'Ymd';
      break;
    case 'weekday':
      $format_str = 'D';
      break;
    default:
      $format_str = 'Y-m-d H:i:s';
      break;
    }
    return date($format_str, $int_time);
  }else{
    return $int_time;
  }
}

function list_field_status(){
  return ['0' => '草稿', '1' => '发布'];
}

function list_field_menu_status(){
  return ['0' => '隐藏', '1' => '显示'];
}

function list_field_user_gender(){
  return ['' => '未知', 'male' => '男', 'female' => '女'];
}

function list_field_article_type(){
  return ['' => '未知', 'News' => '新闻', 'Note' => '笔记'];
}

/**
 * 根据视频的URL地址求出视频来源类型和ID
 * @Author zhanghong
 * @Date   2017-03-05
 * @param  string     $url 视频URL
 * @return array
 */
function match_video_info($url){
  $res = [];
  $type = "";
  $sid = "";
  if(stripos($url, "youku")){
    $type = "youku";
    preg_match('/id_(\S+)\.html/', $url, $matches);
    if(!empty($matches)){
      $sid = $matches[1];
    }
  }else if(stripos($url, "v.qq")){
    $type = "qq";
    preg_match('/\/(\w+)\.html/', $url, $matches);
    if(!empty($matches)){
      $sid = $matches[1];
    }
    if(Str::startsWith($sid, "c")){
      $sid = Str::substr($sid, 1);
    }
  }
  $res = ["type" => $type, "sid" => $sid];
  return $res;
}

/**
 * 上传单张图片--系统自带的旧方法
 * @Author   zhanghong
 * @DateTime 2016-05-04
 * @param    string     $backcall 回调字段名
 * @param    integer    $width    图片高度
 * @param    integer    $height   图片宽度
 * @param    string     $image    当前图片路径
 * @param    string     $backcall_name    回调字段ID
 */
function upload_image($backcall='image', $width=100, $height=100, $image="", $backcall_name=''){
    if(empty($backcall_name)){
      $backcall_name = $backcall;
    }
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.url('admin/upload/create').'?width='.$width.'&height='.$height.'&backcall='.$backcall.'&image='.$image.'&backcall_name='.$backcall_name.'"></iframe>
         <input type="hidden" name="'.$backcall_name.'" id="'.$backcall.'">';
}

/**
 * 上传单张图片--系统自带的旧方法
 * @Author   zhanghong
 * @DateTime 2016-05-04
 * @param    string     $backcall 回调字段名
 * @param    integer    $width    图片高度
 * @param    integer    $height   图片宽度
 * @param    string     $id    当前图片对象ID
 * @param    string     $backcall_name    回调字段ID
 */
function upload_image_id($backcall='image', $width=100, $height=100, $id='', $backcall_name=''){
    if(empty($backcall_name)){
      $backcall_name = $backcall;
    }
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.url('index/upload/add').'?width='.$width.'&height='.$height.'&backcall='.$backcall.'&id='.$id.'&backcall_name='.$backcall_name.'"></iframe>
         <input type="hidden" name="'.$backcall_name.'" id="'.$backcall.'">';
}

function truncate($str, $length = 10, $truncate_string = '…'){
  $len = Str::length($str);
  if($len > $length){
    $sub_str = Str::substr($str, 0, $length);
    $val = $sub_str.$truncate_string;
  }else{
    $val = $str;
  }
  return $val;
}

/**
 * 检查是否是以手机浏览器进入(IN_MOBILE)
 */
function is_mobile_terminal() {
  $mobile = [];
  $mobile_browser_list = 'Mobile|iPhone|Android|WAP|NetFront|JAVA|OperasMini|UCWEB|WindowssCE|Symbian|Series|webOS|SonyEricsson|Sony|BlackBerry|Cellphone|dopod|Nokia|samsung|PalmSource|Xphone|Xda|Smartphone|PIEPlus|MEIZU|MIDP|CLDC';

  $user_agent = think\Request::instance()->header('user-agent');

  // note 获取手机浏览器
  if (preg_match ( '/$mobile_browser_list/i', $user_agent, $mobile )) {
    return true;
  } else {
    if (preg_match ( '/(mozilla|chrome|safari|opera|m3gate|winwap|openwave)/i', $user_agent)) {
      return false;
    } else {
      $param_mobile = think\Request::instance()->param('mobile');
      if ($param_mobile == 'yes') {
        return true;
      } else {
        return false;
      }
    }
  }
}

/**
 * 获取缩略图
 * @param unknown_type $filename 原图路劲、url
 * @param unknown_type $width 宽度
 * @param unknown_type $height 高
 * @param unknown_type $cut 是否切割 默认不切割
 * @return string
 */
function get_thumb_image($filename, $width = 100, $height = 'auto',$cut=false, $replace = false){
  $upload_path = "";
  $info = pathinfo($filename);
  $oldFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '.' . $info['extension'];
  $thumbFile = $info['dirname'] . DIRECTORY_SEPARATOR . $info['filename'] . '_' . $width . '_' . $height . '.' . $info['extension'];

  $oldFile = str_replace('\\', '/', $oldFile);
  $thumbFile = str_replace('\\', '/', $thumbFile);

  $filename = ltrim($filename, '/');
  $oldFile = ltrim($oldFile, '/');
  $thumbFile = ltrim($thumbFile, '/');
  //原图不存在直接返回
  if (!file_exists($upload_path . $oldFile)) {
    @unlink($upload_path . $thumbFile);
    $info['src'] = $oldFile;
    $info['width'] = intval($width);
    $info['height'] = intval($height);
    return $info;
  //缩图已存在并且 replace替换为false
  } elseif (file_exists($upload_path . $thumbFile) && !$replace) {
    $imageinfo = getimagesize($upload_path . $thumbFile);
    //dump($imageinfo);exit;
    $info['src'] = $thumbFile;
    $info['width'] = intval($imageinfo[0]);
    $info['height'] = intval($imageinfo[1]);
    return $info;
  //执行缩图操作
  } else {
    $oldimageinfo = getimagesize($upload_path . $oldFile);
    $old_image_width = intval($oldimageinfo[0]);
    $old_image_height = intval($oldimageinfo[1]);
    if ($old_image_width <= $width && $old_image_height <= $height) {
      @unlink($upload_path . $thumbFile);
      @copy($upload_path . $oldFile, $upload_path . $thumbFile);
      $info['src'] = $thumbFile;
      $info['width'] = $old_image_width;
      $info['height'] = $old_image_height;
      return $info;
    } else {
      //生成缩略图 - 更好的方法
      if ($height == "auto") $height = 0;
      if ($width == "auto") $width = 0;
      think\Loader::import("PhpThumb.PhpThumbFactory", EXTEND_PATH, '.class.php');
      try{
        $thumb = \PhpThumbFactory::create($upload_path . $filename);
        if ($cut) {
          $thumb->adaptiveResize($width, $height);
        } else {
          $thumb->resize($width, $height);
        }
        $res = $thumb->save($upload_path . $thumbFile);
      }catch(\Exception $e){
        $res = NULL;
      }

      //缩图失败
      if (!$res) {
        $thumbFile = $oldFile;
      }
      $info['width'] = $width;
      $info['height'] = $height;
      $info['src'] = $thumbFile;
      return $info;
    }

  }
}


function get_thumb_src($picture_path, $width = 100, $height = 'auto', $cut = false, $replace = false){
  if(empty($picture_path)){
    return '';
  }
  $attach = get_thumb_image($picture_path, $width, $height, $cut, $replace);

  return '/'.$attach['src'];
}